package com.duke.shaking.profile;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import com.androidquery.AQuery;
import com.duke.shaking.R;
import com.duke.shaking.TitleActivity;
import com.duke.shaking.interaction.ChatActivity;
import com.duke.shaking.more.VIPUpgradeActivity;
import com.duke.shaking.net.AsyncHttpResponseWithResultHandler;
import com.duke.shaking.net.MessageSender;
import com.duke.shaking.net.NetUtils;
import com.duke.shaking.pojo.ChatFriend;
import com.duke.shaking.pojo.Message;
import com.duke.shaking.pojo.User;
import com.duke.shaking.storage.DataManager;
import com.duke.shaking.utils.AppUtils;
import com.duke.shaking.utils.PrefUtils;
import com.duke.shaking.widget.FormRow;

public class FriendProfileActivity extends TitleActivity {

	private ChatFriend friend;
	private boolean isNewFriend;
	private boolean isFirstSend;
	private int photosCount;
	
	private ImageView btn_sayHello;
	private AQuery aQuery;
	
	public FriendProfileActivity() {
		aQuery = new AQuery(this);
	}
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        friend = (ChatFriend)getIntent().getSerializableExtra("friend");
        isNewFriend = getIntent().getBooleanExtra("isNewFriend", false);
        isFirstSend = true;
        
        btn_sayHello = (ImageView)findViewById(R.id.btn_sayHello);
        if (btn_sayHello != null) {
        	if (isNewFriend) {
        		btn_sayHello.setVisibility(View.VISIBLE);
        	}
        	else {
        		btn_sayHello.setVisibility(View.GONE);
        	}
        }
        
        initData();
	}
	
	private void setVipIcon(int level, View vip, View vipYear) {
    	if (level <= 0) {
    		if (vip != null) {
    			vip.setVisibility(View.GONE);
    		}
    		if (vipYear != null) {
    			vipYear.setVisibility(View.GONE);
    		}
    	}
    	else if (level < User.level_vip_year) {
    		if (vip != null) {
    			vip.setVisibility(View.VISIBLE);
    		}
    		if (vipYear != null) {
    			vipYear.setVisibility(View.GONE);
    		}
    	}
    	else {
    		if (vip != null) {
    			vip.setVisibility(View.GONE);
    		}
    		if (vipYear != null) {
    			vipYear.setVisibility(View.VISIBLE);
    		}
    	}
	}
	
	private void initData() {
		AsyncHttpResponseWithResultHandler responseHandler = new AsyncHttpResponseWithResultHandler(){
			
        	@Override
			public void onResultSuccess(String response) {
				super.onResultSuccess(response);
				
				JSONObject jsonObj = this.getBody(response);
				showInfo(jsonObj);
			}

			@Override
			public void onResultFailure(String result) {
				super.onResultFailure(result);
			}
        };
        
        NetUtils.getFriendInfo(this, responseHandler, friend.getUserId());
	}
	
	private void showInfo(JSONObject jsonObj) {
		String avatarUrl = jsonObj.optString("photo");
		if(avatarUrl != null && !avatarUrl.trim().equals("")) {
			aQuery.id(R.id.avatar).image(avatarUrl, false, true, 0, R.drawable.blank_avatar);
		}
		String nickname = jsonObj.optString("nickname");
		if(nickname != null && !nickname.trim().equals("")) {
			aQuery.id(R.id.txt_nickname).text(nickname);
		}
		int age = jsonObj.optInt("age");
		if(age != 0) {
			aQuery.id(R.id.txt_age).text(String.valueOf(age) + getString(R.string.age_year));
		}
		String city = jsonObj.optString("city_1");
		if(city != null && !city.trim().equals("")) {
			String sex = "";
			if (friend.getSex() != null) {
				if (friend.getSex() == User.sex_male) {
					sex = getString(R.string.single_male);
				} else if (friend.getSex() == User.sex_female) {
					sex = getString(R.string.single_female);
				}
			}
			aQuery.id(R.id.txt_local).text(city + sex);
		}
		
		/*String userId = jsonObj.optString("userid");
		if(userId != null && !userId.trim().equals("")) {
			FormRow userIdRow = (FormRow)this.findViewById(R.id.row_id);
			if(userIdRow != null) {
				userIdRow.setText(userId);
			}
		}*/
		String sign = jsonObj.optString("remark");
		FormRow signRow = (FormRow)this.findViewById(R.id.row_sign);
		if(sign != null && !sign.trim().equals("")) {
			if(signRow != null) {
				signRow.setText(sign);
			}
		} else {
			String strSex = "";
			if(friend.getSex() != null) {
				strSex = (friend.getSex() == User.sex_female ? getString(R.string.she) : getString(R.string.he));
			}
			String txt = String.format(getString(R.string.label_invite_to_update_profile), strSex);
			signRow.setText(txt);
			signRow.setOnClickMethod("onInviteUpdateProfile");
		}
		photosCount = jsonObj.optInt("photos");
		FormRow photosRow = (FormRow)this.findViewById(R.id.row_photo);
		if(photosRow != null) {
			if (photosCount <= 0) {
				photosRow.setText(getString(R.string.label_photos_0_count));
			}
			else {
				photosRow.setText(String.format(getString(R.string.label_take_a_look), photosCount));
			}
		}
		int level = jsonObj.optInt("level");
		setVipIcon(level, 
        		findViewById(R.id.img_vip),
        		findViewById(R.id.img_vipyear));
	}
	
	@Override
	protected int getLayoutId() {
		// TODO Auto-generated method stub
		return R.layout.activity_friend_profile;
	}

	@Override
	protected void onTitleInit() {
		// TODO Auto-generated method stub
		initTitle(TITLE_BTN_EXIST | TITLE_BTN_BACK,
				R.string.back,
				0,
				0,
				R.string.title_view_profile);
	}
	
	public void sayHello(View view) {
		
		go(ChatActivity.class, "friend", friend);
	}
	
	/**
	 * Click the "view photos" link
	 * @param v
	 */
	public void viewPhotos(View v) {
		if (photosCount <= 0) {
			onInviteUpdateProfile(v);
		}
		else if(me.getLevel() == null || me.getLevel() <= 0) {
			gotoBuyService(getString(R.string.alert_view_friend_photo_msg));
		} else {
			Intent intent = new Intent(this, FriendPhotosActivity.class);
			intent.putExtra("friend", friend);
			intent.putExtra("isNewFriend", isNewFriend);
			startActivity(intent);
		}
	}
	
	private void gotoBuyService(String msg) {
		Builder builder = new Builder(this);
		builder.setMessage(msg).setPositiveButton(R.string.btn_upgrade_to_view_photo, 
			new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					go(VIPUpgradeActivity.class);
					dialog.dismiss();
				}
			});
			builder.setNegativeButton(R.string.cancel, new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
		
		AlertDialog alert = builder.create();
		alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        alert.show();
	}
	
	
	public void onInviteUpdateProfile(View v) {
		PrefUtils prefUtils = PrefUtils.getInstance(this, getString(R.string.updateProfilePref));
		String fuid = friend.getUserId();
		String tag = (String)v.getTag();
		Log.i(TAG, "tag: " + tag);
		String pKey = fuid;
		if (tag != null) {
			pKey = fuid + "-" + tag;
		}
		String strRemindDate = prefUtils.getString(pKey, null);
		boolean bSendMsg = false;
		Date now = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		if(strRemindDate == null) {
			bSendMsg = true;
		} else {
			try {
				Date sendDate = format.parse(strRemindDate);
				if(AppUtils.isSameDay(sendDate, now)) {
					// already send one time
					Builder builder = new Builder(this);
					builder.setMessage(getString(R.string.alert_already_invite_update_profile)).
						setPositiveButton(R.string.ok, new OnClickListener() {
						
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
					
					AlertDialog alert = builder.create();
					alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
			        alert.show();
				} else {
					bSendMsg = true;
				}
			} catch (ParseException e) {
			}
		}
		
		if (bSendMsg) {
			prefUtils.addString(pKey, format.format(now));
			
			String msg = getString(R.string.invite_to_update_profile_default_msg);
			String label = null;
			if(tag != null) {
				if("signature".equalsIgnoreCase(tag)) {
					label = getString(R.string.signature);
					msg = String.format(getString(R.string.invite_to_update_profile_msg), label);
				}
				else if ("photo".equalsIgnoreCase(tag)) {
					msg = getString(R.string.invite_to_update_profile_photo);
				}
			}
			Log.i(TAG, "msg:" + msg);
			sendUpdateProfileInvitation(msg);
		}
	}
	
	private void sendUpdateProfileInvitation(String strMsg) {
		if (friend == null || me == null || !me.hasLogin()) {
			return;
		}
		
		Message msg = new Message();
		msg.setContent(strMsg);
		msg.setDirection(Message.MSG_DIRECTION_TO);
		msg.setToId(friend.getUserId());
		
		msg.setFromId(me.getUserId());
		msg.setUnread(false);
		msg.setSendState(Message.SEND_STATE_SENDING);
		msg.setTimestamp(new Date());
		msg.setRecvTime(new Date());
		if (isFirstSend) {
			if (DataManager.getShared().getFriendById(friend.getUserId()) == null) {
				DataManager.getShared().putOrUpdateFriend(friend);
			}
			isFirstSend = false;
		}
		long msgId = DataManager.getShared().putMessage(msg);
		if (msgId < 0) {
			toast("");
			return;
		}
		
		msg.setMsgId(msgId);
		
		MessageSender.getShared().sendMsg(msg);
		toast(R.string.alert_invite_sent);
	}

}
